﻿using IV.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IV.Components.Log
{
    /// <summary>
    /// LogControl.xaml 的交互逻辑
    /// </summary>
    public partial class LogControl : UserControl
    {
        public LogControl()
        {
            InitializeComponent();
            DataContext = CommonServiceLocator.ServiceLocator.Current.GetInstance<LogComponent>();
            ((INotifyCollectionChanged)ic1.Items).CollectionChanged += (s, e) => SetItemsControlScrollTrack(ic1);
            ((INotifyCollectionChanged)ic2.Items).CollectionChanged += (s, e) => SetItemsControlScrollTrack(ic2);
            ((INotifyCollectionChanged)ic3.Items).CollectionChanged += (s, e) => SetItemsControlScrollTrack(ic3);
            ((INotifyCollectionChanged)ic4.Items).CollectionChanged += (s, e) => SetItemsControlScrollTrack(ic4);
        }

        // 滚动跟踪
        private void SetItemsControlScrollTrack(ItemsControl control)
        {
            var listViewScrollviewer = control.Parent as ScrollViewer;
            if (listViewScrollviewer != null)
            {
                if (listViewScrollviewer.VerticalOffset == listViewScrollviewer.ScrollableHeight)
                {
                    listViewScrollviewer.ScrollToBottom();
                }
            }
        }

        private void CollectionViewSource_ErrorFilter(object sender, FilterEventArgs e)
        {
            var item = e.Item as LogItem;
            e.Accepted = item != null && item.LogLevel == Core.Enums.ELogLevel.ERROR;
        }
        private void CollectionViewSource_WarnFilter(object sender, FilterEventArgs e)
        {
            var item = e.Item as LogItem;
            e.Accepted = item != null && item.LogLevel == Core.Enums.ELogLevel.WARN;
        }
        private void CollectionViewSource_InfoFilter(object sender, FilterEventArgs e)
        {
            var item = e.Item as LogItem;
            e.Accepted = item != null && item.LogLevel == Core.Enums.ELogLevel.INFO;
        }


        private void PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (!e.Handled)
            {
                e.Handled = true;

                // 激发一个鼠标滚轮事件，冒泡给外层接收到
                var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
                eventArg.RoutedEvent = UIElement.MouseWheelEvent;
                eventArg.Source = sender;
                var parent = ((Control)sender).Parent as UIElement;
                parent?.RaiseEvent(eventArg);
            }
        }
    }
}
